using System;
using System.Collections.Generic;
using GameFramework.Battle.Core;
using Gameplay.PVE.Entity;
using Gameplay.PVE.Utils;
using UnityEngine;
using Yoozoo.Framework.Managers;
using Yoozoo.Managers;
using Yoozoo.Gameplay.RTS;
using Yoozoo.Gta.Common;

namespace Gameplay.PVE
{
	public class PveCard
	{
		public int id;
		public int configId;
		public int skillId;
		public int skillLevel;
		public int cost;
		public int unitId;
		public int heroId;
		public int type;
		public PveCardState state;
	}

	public enum PveCardState
	{
		InDeck,
		InHand,
		InGrave,
	}

    public class PveCardManager
    {
        private static PveCardManager instance;
        public static PveCardManager Instance
        {
	        get
	        {
		        if (instance == null)
		        {
			        instance = new PveCardManager();
		        }
		        return instance;
	        }
        }
        public void Init()
        {
						
        }

        private List<PveCard> cards = new List<PveCard>();//全部的卡
        
        public List<PveCard> deck = new List<PveCard>();
        public List<PveCard> hand = new List<PveCard>();
        public List<PveCard> grave = new List<PveCard>();

        public List<PveCard> autoCastList = new List<PveCard>();
        private int currentAutoCastIndex;

        //根据当前手牌和卡组生成自动释放技能的列表
        public void RefreshAutoCastList()
        {
			autoCastList.Clear();
			for (int i = 0; i < hand.Count; i++)
			{
				autoCastList.Add(hand[i]);
			}

			for (int i = 0; i < deck.Count; i++)
			{
				autoCastList.Add(deck[i]);
			}

			currentAutoCastIndex = 0;
        }

        public int GetAutoCastUnitId()
        {
	        if (currentAutoCastIndex >= autoCastList.Count)
	        {
		        currentAutoCastIndex = 0;
	        }

	        if (autoCastList.Count > currentAutoCastIndex)
	        {
		        return autoCastList[currentAutoCastIndex].unitId;
	        }

	        return -1;
        }
        
        public void OnAutoCastCard()
        {
	        /*var castCard = autoCastList[0]; 
	        autoCastList.RemoveAt(0);
	        autoCastList.Add(castCard);*/
	        if (currentAutoCastIndex < autoCastList.Count)
	        {
		        PveCard card = autoCastList[currentAutoCastIndex];
		        var index = hand.FindIndex((o)=>o == card);
		        if (index >= 0)
		        {
			        Cast(index);
		        }

	        }
	        currentAutoCastIndex++;
	        if (currentAutoCastIndex >= autoCastList.Count)
	        {
		        currentAutoCastIndex = 0;
	        }
        }

        public void OnAutoCastCardUseMp(int unitId)
        {
	        for (int i = 0; i < hand.Count; i++)
	        {
		        if (hand[i].unitId == unitId)
		        {
			        Cast(i);
			        return;
		        }
	        }
        }

        //新增我方支援角色
        public void AddSkill(BattleUnit unit)
        {
	        var newCard = new PveCard
	        {
		        unitId = unit.Data.id,
		        id = cards.Count,
		        skillId = unit.Data.rpgSkillId,
		        skillLevel = unit.Data.rpgSkillInitiativeLevel,
		        cost = unit.Data.rpgSkillCost,
		        heroId = unit.Data.heroId,
		        state = PveCardState.InDeck,
	        };
	        cards.Add(newCard);
	        deck.Add(newCard);
	        autoCastList.Add(newCard);
	        if (readyToCastIndex >= 0)
            {
	            readyToAddCount++;
	            return;
            }
            readyToCastIndex = -1;
	        CheckNeedDraw();
        }
        
		public void RpgStart()
		{
			var list = UnitManager.Instance.GetAllUnitByTeam(0);

			readyToAddCount = 0;
			cards.Clear();
			deck.Clear();
			hand.Clear();
			grave.Clear();
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].Data.rpgInitiativeSkillConfig == null || list[i].Data.isSummonUnit)
				{
					continue;
				}
				cards.Add(new PveCard
				{
					unitId = list[i].Data.id,
					id = cards.Count,
					skillId = list[i].Data.rpgSkillId,
					skillLevel = list[i].Data.rpgSkillInitiativeLevel,
					cost = list[i].Data.rpgSkillCost,
					heroId = list[i].Data.heroId,
					state = PveCardState.InDeck,
				});
			}

			readyToCastIndex = -1;
			readyToDeleteUnit = -1;
			/*cards.Add(new PveCard
			{
				unitId = 0,
				id = cards.Count,
				skillId = (int)ESkillId.basicSkill1,
				cost = 1,
				state = PveCardState.InDeck,
			});
			cards.Add(new PveCard
			{
				unitId = 0,
				id = cards.Count,
				skillId = (int)ESkillId.basicSkill2,
				cost = 2,
				state = PveCardState.InDeck,
			});*/
			/*cards.Add(new PveCard
			{
				unitId = 0,
				id = cards.Count,
				skillId = (int)ESkillId.basicSkill3,
				cost = 3,
				state = PveCardState.InDeck,
			});
			cards.Add(new PveCard
			{
				unitId = 0,
				id = cards.Count,
				skillId = (int)ESkillId.basicSkill4,
				cost = 2,
				state = PveCardState.InDeck,
			});*/
			/*cards.Add(new PveCard
			{
				unitId = 0,
				id = cards.Count,
				skillId = (int)ESkillId.basicSkill5,
				cost = 4,
				state = PveCardState.InDeck,
			});*/

			/*for (int i = 0; i < 2; i++)//召唤
			{
				cards.Add(new PveCard
				{
					unitId = 0,
					type = 3,
					id = cards.Count,
					skillId = 301 + i,
					cost = 2,
					state = PveCardState.InDeck,
				});
			}
			
			cards.Add(new PveCard
			{
				unitId = 0,
				type = 3,
				id = cards.Count,
				skillId = 306,
				cost = 2,
				state = PveCardState.InDeck,
			});*/

			/*for (int i = 0; i < PveUtils.deckCards.Count; i++)
			{
				int type = 1;
				int id = PveUtils.deckCards[i];
				if (id > 300)
				{
					type = 3;
				}
				else if (id > 200)
				{
					type = 2;
				}
				cards.Add(new PveCard
				{
					unitId = 0,
					type = type,
					id = cards.Count,
					skillId = id,
					cost = PveUtils.GetCostByCardId(id),
					state = PveCardState.InDeck,
				});
			}



			var mainUnit = UnitManager.Instance.GetUnit(0);
			//为英雄添加卡牌
			for (int i = 0; i < cards.Count; i++)
			{
				if (cards[i].type == 1)//是武器卡
				{
					var config = PveUtils.GetSkillConfig(cards[i].skillId);
					var weaponConfig = PveUtils.GetWeaponConfig(config.weaponId);
					for (int j = 0; j < list.Count; j++)
					{
						if (list[j].Data.config.weaponType == weaponConfig.type || list[j].Data.id == cards[i].unitId)
						{
							var arg = ClassManager.Get<AddCardSkillArg>();
							arg.skillId = cards[i].skillId;
							arg.cardType = cards[i].type;
							list[j].Transmit(ETransmitType.AddCardSkill,arg);
						}
					}
				}
				else if (cards[i].type == 2) //是即时卡
				{
					var arg = ClassManager.Get<AddCardSkillArg>();
					arg.skillId = cards[i].skillId;
					arg.cardType = cards[i].type;
					mainUnit.Transmit(ETransmitType.AddCardSkill,arg);
				}
				else if (cards[i].type == 3) //是召唤卡
				{
					var arg = ClassManager.Get<AddCardSkillArg>();
					arg.skillId = cards[i].skillId;
					arg.cardType = cards[i].type;
					mainUnit.Transmit(ETransmitType.AddCardSkill,arg);
				}
			}*/
			
			for (int i = 0; i < cards.Count; i++)
			{
				deck.Add(cards[i]);
				Debug.Log("lgz cards" + " id: " + cards[i].id + " skill id: " + cards[i].skillId);
			}
			
			//Shuffle();
			CheckNeedDraw();
			//RefreshUI();
		}

		public List<Vector3Int> GetHandToLua()
		{
			var hand = new List<Vector3Int>();
			for (int i = 0; i < this.hand.Count; i++)
			{
				hand.Add(new Vector3Int(this.hand[i].skillId,this.hand[i].cost,this.hand[i].heroId));
			}

			return hand;
		}

		public Vector2Int GetNextToLua()
		{
			if (cards.Count == 0)
			{
				return new Vector2Int(0, 0);
			}
			//var nextCard = deck[deck.Count - 1];
			var nextCard = cards[0];
			var next = new Vector2Int(nextCard.skillId, nextCard.cost);
			return next;
		}
		
		private void RefreshUI()
		{
			for (int i = 0; i < hand.Count; i++)
			{
				RefreshSingleCard(i);
			}
			//LuaManager.mainState.GetFunction("pveManager.RefreshCards").Call(GetHandToLua());
		}

		private void RefreshSingleCard(int index,bool isDead = false)
		{
			if (index == -1)
			{
				return;
			}

			int sort = index;
			int cardId = 0;//hand[index].skillId;
			int heroId = 0;//hand[index].heroId;
			if (index < hand.Count && !isDead)
			{
				cardId = hand[index].skillId;
				heroId = hand[index].heroId;
			}
			ResidentHandler.Inst.GetFunction("pveManager.RefreshCard").Action(sort, cardId, heroId,PveManager.Instance.teamEnergy);
		}

		private void FreezeCard(int index)
		{
			if (index == -1)
			{
				return;
			}
			ResidentHandler.Inst.GetFunction("pveManager.FreezeCard").Action(index);
		}
		
		public void Shuffle()
		{
			BattleUtils.Shuffle(ref deck);
		}
		
		public void Draw(int index = -1)
		{	
			if (deck.Count == 0)
			{
				return;
			}
			var card = deck[deck.Count - 1];
			deck.RemoveAt(deck.Count - 1);
			if (index == -1 || index >= hand.Count)
			{
				hand.Add(card);
				index = hand.Count-1;
			}
			else
			{
				hand.Insert(index,card);
			}
			card.state = PveCardState.InHand;
			//Debug.LogError("抽卡");
			//RefreshUI(index);
			RefreshSingleCard(index);
		}

		private void ResetCards(PveCard card)
		{
			//释放卡牌
			int index = cards.IndexOf(card);
			cards.Remove(card);
			for (int i = index; i < cards.Count; i++)
			{
				cards[i].id = i;
			}
			deck.Clear();
			hand.Clear();
			autoCastList.Remove(card);
			for (int i = 0; i < cards.Count; i++)
			{
				deck.Add(cards[i]);
			}
			//Shuffle();
			CheckNeedDraw();
		}

		public void OnUnitDead(int id)
		{
			bool isUnitInCard = false;
			for (int i = 0; i < cards.Count; i++)
			{
				if (cards[i].unitId == id)
				{
					isUnitInCard = true;
					break;
				}
			}

			if (!isUnitInCard)
			{
				return;
			}
			if (readyToCastIndex >= 0)
			{
				var currentCard = hand[readyToCastIndex];
				if (currentCard.unitId != id)
				{
					//正在施法的人没有死亡，等施法完成后再删除卡牌
					readyToDeleteUnit = id;
					return;
				}
			}
			readyToCastIndex = -1;
			if (!PveGlobalVlues.UseHeroMp)
			{
				for (int i = 0; i < hand.Count; i++)
				{
					if (hand[i].unitId == id)
					{
						var before = hand.Count;
						ResetCards(hand[i]);
						if (hand.Count != before)
						{
							RefreshUI();
						}
						return;
					}
				}
			
				for (int i = 0; i < deck.Count; i++)
				{
					if (deck[i].unitId == id)
					{
						ResetCards(deck[i]);
						return;
					}
				}
			}
			else
			{
				for (int i = 0; i < hand.Count; i++)
				{
					if (hand[i].unitId == id)
					{
						ResidentHandler.Inst.GetFunction("pveManager.SetIsHeroDead").Action(hand[i].heroId, true);
						return;
					}
				}
				
			}
		}

		public void Cast(int index)
		{
			var card = hand[index];
			//Debug.LogError("使用"+index);
			if (PveGlobalVlues.UseHeroMp)
			{
				var unit = UnitManager.Instance.GetUnit(card.unitId);
				unit.SetMpChange(-unit.Data.mpCost);
			}
			else
			{
				if (PveManager.Instance.teamEnergy < card.cost)
				{
					return;
				}
				PveManager.Instance.teamEnergy -= card.cost;
			}

			OperationManager.Instance.BeforeReleaseCard(index);
			readyToCastIndex = -1;
			FreezeCard(index);
			ResidentHandler.Inst.GetFunction("L_Trigger.UsePveCard").Action(card.heroId);
			TimeManager.Instance.DelayCall(200, () =>
			{
				if (readyToDeleteUnit >= 0)
				{
					OnUnitDead(readyToDeleteUnit);
				}

				if (readyToAddCount > 0)
				{
					CheckNeedDraw();
					readyToAddCount = 0;
				}
				if (!hand.Contains(card))
				{
					//已经死了，卡牌被删除了
				}
				else
				{
					for (int i = 0; i < hand.Count; i++)
					{
						if (hand[i] == card)
						{
							index = i;
							hand.RemoveAt(i);
							break;
						}
					}
					deck.Insert(0,card);
					card.state = PveCardState.InDeck;
				}
				Draw(index);
			});
			//CheckNeedDraw();
		}
		
		private int readyToCastIndex = -1;
		private int readyToDeleteUnit = -1;

		private int readyToAddCount = 0;

		public void ReadyToCast(int index)
		{
			readyToCastIndex = index;
		}

		public void CancelCast()
		{
			readyToCastIndex = -1;
			if (readyToDeleteUnit >= 0)
			{
				OnUnitDead(readyToDeleteUnit);
			}
			if (readyToAddCount > 0)
			{
				CheckNeedDraw();
				readyToAddCount = 0;
			}
			
		}

		public void CheckNeedDraw()
		{
			int drawCardNum = UnitManager.Instance.GetAllUnitCountByTeam(0);
			int count = drawCardNum - hand.Count; //需要抽牌数量
			
			for (int i = 0; i < count; i++)
			{
				Draw();
			}
		}

		public BattleUnit GetCastUnit(int index)
		{
			if (hand.Count <= index)
			{
				return null;
			}
			var card = hand[index];
			int unitId = card.unitId;
			return UnitManager.Instance.GetUnit(unitId);
		}

		public int GetSkillIdByIndex(int index)
		{
			var card = hand[index];
			return card.skillId;
		}

		public int GetSkillLevelByIndex(int index)
		{
			var card = hand[index];
			return card.skillLevel;
		}

		public int GetHeroIdByIndex(int index)
		{
			var card = hand[index];
			return card.heroId;
		}
		
		public List<int> GetWeaponSkillByWeaponType(int type)
		{
			List<int> skills = new List<int>();
			for (int i = 0; i < cards.Count; i++)
			{
				if (cards[i].type == 1)//是武器卡
				{
					var config = PveUtils.GetSkillConfig(cards[i].skillId);
					var weaponConfig = PveUtils.GetWeaponConfig(config.weapon_id);
					if (type == weaponConfig.type)
					{
						skills.Add(cards[i].skillId);
					}
				}
			}

			return skills;
		}
		
    }
}
